package com.zhangjk.controller;

import cn.javaer.aliyun.sms.SmsClient;
import com.aliyuncs.utils.StringUtils;
import com.sun.org.apache.regexp.internal.RE;
import com.zhangjk.enums.AppConstant;
import com.zhangjk.enums.ResultEnum;
import com.zhangjk.enums.UserEnum;
import com.zhangjk.exception.CheckException;
import com.zhangjk.pojo.RegisterVo;
import com.zhangjk.pojo.User;
import com.zhangjk.pojo.userVo.UserInfo;
import com.zhangjk.pojo.userVo.UserVo;
import com.zhangjk.service.UserService;
import com.zhangjk.util.*;
import com.zhangjk.util.httpClient.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangjk on 2019/4/21.
 */
@RestController
@Api(description = "用户认证__(移动端)")
@RequestMapping("/auth")
public class LoginController {


    // 获取手机验证码组件
    @Autowired
    private SmsClient smsClient;

    // 用户组件
    @Autowired
    private UserService userService;

   @ApiOperation(value = "获取手机验证码", notes = "")
    @RequestMapping(value = "/sendCode",method = RequestMethod.GET)
   @ApiImplicitParams({
           @ApiImplicitParam(name = "phone", value = "手机号", paramType = "query", required = true, dataType = "String")

   })
    public Object getList(@RequestParam("phone") String  phone, HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(!CheckUtil.isPhone(phone)){
            throw new CheckException(ResultEnum.PARAM_ERROR_PHONE);
        }
        int authentication=0;
        try {
            authentication = this.smsClient.sendVerificationCode("authentication", phone);
        }catch (IllegalArgumentException e){
                throw new CheckException(ResultEnum.ERROR_FAIL);
        }

        System.out.println(authentication);
        Date date = new Date();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String time = sdf.format(date);

        String result = authentication + "#" + URLEncoder.encode(time);

        return ResultVOUtil.success(result);
    }
    @ApiOperation(value = "注册手机号", notes = "")
    @RequestMapping(value = "/RegisterPhone",method = RequestMethod.POST)
    public ResponseMessage RegisterPhone(@RequestBody RegisterVo  registerVo, HttpServletRequest request) throws  Exception {

        if(!CheckUtil.isPhone(registerVo.getPhone())){
            throw new CheckException(ResultEnum.PARAM_ERROR_PHONE);
        }
        if(StringUtils.isEmpty(registerVo.getCode())){
            throw new CheckException(ResultEnum.PARAM_ERROR_VICODE);
        }
        return userService.RegisterPhone(registerVo.getPhone(),registerVo.getCode(),request);
    }

    //退出登录
    @RequestMapping("/loginOut")
    public Object loginOut(HttpServletRequest request) {
        HttpSession session = request.getSession();
        if(session.getAttribute("user")!=null){
            session.removeAttribute("user");
        }
        return ResultVOUtil.success("退出成功！");
    }

    @ApiOperation(value = "认证登录", notes = "")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public   ResponseMessage    login(@RequestBody UserVo  userVo, HttpServletRequest  request){
        String   messagecode = request.getHeader(AppConstant.Rande_Code);
        ResponseMessage  responseMessage  =new ResponseMessage();
       String     token ="";
        TokenUtil tokenUtil = new TokenUtil();
        Map<String, String> params=new HashMap<>();
        params.put("appid",AppConstant.AppID);
        params.put("secret",AppConstant.AppSecret);
        params.put("js_code",userVo.getCode());
        params.put("grant_type",AppConstant.grant_type);
        JSONObject jsonObject= HttpClientUtils.getForJsonResult(AppConstant.url,params);
        ResultVo resultVo=JSONUtils.toBean(jsonObject,ResultVo.class);
        JwtToken    jwtToken = new JwtToken();
        System.out.println("错误代码"+resultVo.getErrcode()+"------ 错误消息"+resultVo.getErrmsg());

        if (resultVo.getErrcode()==null && resultVo.getErrmsg()==null){
            System.out.println("成功了");
            jwtToken.setOpenid(resultVo.getOpenid());
            jwtToken.setSession_key(resultVo.getSession_key());
            jwtToken.setExpiration(new Date());

            token = tokenUtil.createJwtString(jwtToken);
            User   user= userService.findbyopenid(resultVo.getOpenid());

            UserInfo  userInfo=new UserInfo();
            if (user!=null){

                if (user.getPhone()==null || user.getPhone().equals("")){
                    userInfo.setToken(token);
                    responseMessage.setResult(userInfo);
                    responseMessage.setStatus(0);
                    responseMessage.setMessage("  已登录 未注册 ");
                }else {

                    if (user.getSczt().equals("1")){


                        BeanUtils.copyProperties(user,userInfo);
                        userInfo.setToken(token);
                        responseMessage.setResult(userInfo);
                        responseMessage.setStatus(3);
                        responseMessage.setMessage("该用户已被管理员禁用 请联系管理员");
                    }else {
                        BeanUtils.copyProperties(user,userInfo);
                        userInfo.setToken(token);
                        responseMessage.setResult(userInfo);
                        responseMessage.setStatus(2);
                        responseMessage.setMessage("已经注册过手机号");

                    }


                }

            }else {
                // 把当前用户的信息增加到数据库
                userService.SaveUser(userVo,resultVo.getOpenid());
                userInfo.setToken(token);
                responseMessage.setResult(userInfo);
                responseMessage.setStatus(0);
                responseMessage.setMessage("登录成功");


            }

        }else {

            responseMessage.setResult("");
            responseMessage.setStatus(1);
            responseMessage.setMessage("登录失败");
        }



         return responseMessage;
    }


    public static void main(String[] args) {

        JwtToken    jwtToken = new JwtToken();
        TokenUtil tokenUtil = new TokenUtil();

        jwtToken.setOpenid("oa7Tc4spLlbtZCeyY0AsGU8kwR3g");
        jwtToken.setSession_key("kjsdigfdjfgiudiojt3453485");
        jwtToken.setExpiration(new Date());
       String   token = tokenUtil.createJwtString(jwtToken);


        System.out.println(token);
    }

}
